package org.zoomdev.zoom.timer.modules;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.common.utils.DateTimeUtils;
import org.zoomdev.zoom.timer.TimerJob;

import java.util.concurrent.atomic.AtomicBoolean;

final class AbandonExistsStrategy implements TimerJob {
    private static final Logger log = LoggerFactory.getLogger(CoreTimerModule.NAME);
    private final TimerJob job;
    private final AtomicBoolean executing = new AtomicBoolean(false);
    private long last;

    public AbandonExistsStrategy(TimerJob job) {
        this.job = job;
    }

    @Override
    public void execute() throws Throwable {
        if (executing.compareAndSet(false, true)) {
            try {
                last = System.currentTimeMillis();
                job.execute();
            } finally {
                executing.set(false);
            }
        } else {
            log.info("已经有任务[{}]正在执行,本次任务放弃执行,上一次执行时间:{}", job, DateTimeUtils.formatToStandardDateTime(DateTimeUtils.toLocalDateTime(last)));
        }
    }
}
